package com.hello;

import java.util.concurrent.*;

/**
 * 多线程下载图片
 * 多张图片并发下载
 */
public class DownloadCallable implements Callable<Boolean> {

    private String url;
    private String name;

    public DownloadCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() {
        Download d = new Download();
        d.download(url, name);
        System.out.println(name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建目标对象
        DownloadCallable dt = new DownloadCallable("http://static2.iocoder.cn/images/Learn/08.png", "jc.jpg");
        DownloadCallable dt2 = new DownloadCallable("http://static2.iocoder.cn/images/Learn/07.png", "yw.jpg");
        DownloadCallable dt3 = new DownloadCallable("http://static2.iocoder.cn/images/Learn/06.png", "gj.jpg");

        // 创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);

        // 提交执行
        Future<Boolean> result1 = service.submit(dt);
        Future<Boolean> result2 = service.submit(dt2);
        Future<Boolean> result3 = service.submit(dt3);

        // 获取结果
        boolean r1 = result1.get();
        boolean r2 = result2.get();
        boolean r3 = result3.get();
        System.out.println(r1);

        // 关闭服务
        service.shutdownNow();

    }
}
